public class HashBuck {
    class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;

    public HashBuck(){
        array = new Node[10];
    }

    public void put(int key,int val){//当有冲突时首先进行冲突点链表存储，此代码利用头插法
        int index = key % array.length;
        Node cur = array[index];
        while (cur.key == key){
            cur.val = val;
            return;
        }
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;

        if (loadFactor() >= 0.75){
            resize();
        }
    }
    private void resize(){ //若冲突率达到0.75时进行扩容操作
        Node[] tmpArr = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                Node curNext = cur.next;
                int newIndex = cur.key % tmpArr.length;
                cur.next = tmpArr[newIndex];
                tmpArr[newIndex] = cur;
                cur = curNext;
            }
        }
        array = tmpArr;
    }
    private double loadFactor(){
        return usedSize*1.0 / array.length;
    }

    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null){
            if (cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
